<?php
class event {
	public		$run_time = 0,
				$tag = null,
                $id = 0;
	protected	$callback = null,
				$parameters = null;
	public function __construct($run_time, $callback, $parameters = array()) {
		if (!is_int($run_time) or (!is_array($callback) and !is_string($callback)) or !is_array($parameters))
			throw new Exception("Bad parameters for __construct of event",008);
		$this->run_time = $run_time;
		if (!isset($GLOBALS['events_by_time'][$run_time]))
			$GLOBALS['events_by_time'][$run_time] = array();
		$GLOBALS['events_by_time'][$run_time][] =& $this;
        $this->id = count($GLOBALS['events_by_id']);
        $GLOBALS['events_by_id'][] =& $this;
	}
	public function destruct() {
        unset($GLOBALS['events_by_id'][$this->id]);
		if (!isset($GLOBALS['events_by_time'][$run_time]))
			return true;
		foreach ($GLOBALS['events_by_time'][$run_time] as $key => &$event) {
			if ($event === $this) {
				unset($GLOBALS['events_by_time'][$run_time][$key]);
				return true;
			}
		}
		return false;
	}
	public function execute($destroy = true) {
		call_user_func_array($this->callback, $this->parameters);
		if ($destroy)
			$this->destruct();
	}
}
function events_execute($delay = 1) {
	if ($GLOBALS['events_last_execution'] + $delay > time())
		return false;
	$GLOBALS['events_last_execution'] = time();
	foreach ($GLOBALS['events_by_time'] as $time => $events) {
		if ($time > time()) return true;
		if (!is_array($events) or empty($events)) {
			unset($GLOBALS['events_by_time'][$time]);
			continue;
		}
		foreach ($events as &$event) {
			$event->execute();
        }
    }
    return true;
}
?>
